<template>
  <div class="side-container" :class="{ 'is-collapse': isCollapse }">
    <!-- 展开/收起按钮 -->
    <div class="toggle-wrapper">
      <div class="collapse-btn" @click="toggleCollapse">
        <el-icon class="collapse-icon" :class="{ 'is-collapse': isCollapse }">
          <component :is="isCollapse ? icons.DArrowRight : icons.DArrowLeft" />
        </el-icon>
      </div>
    </div>

    <!-- 菜单容器 -->
    <div class="menu-wrapper">
      <el-menu
        router
        :default-active="activeMenu"
        :collapse="isCollapse"
        class="el-menu-vertical"
        :unique-opened="true"
        :collapse-transition="true"
        @select="handleSelect"
      >
        <el-sub-menu 
          v-for="item in menuList" 
          :key="item.index" 
          :index="item.index"
          popper-class="custom-popper"
        >
          <template #title>
            <el-icon>
              <component :is="item.icon" />
            </el-icon>
            <span>{{ item.name }}</span>
          </template>
          <el-menu-item
            v-for="child in item.children"
            :key="child.index"
            :index="child.index"
            :class="{'is-active': activeIndex === child.index}"
          >
            {{ child.name }}
          </el-menu-item>
        </el-sub-menu>
      </el-menu>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { DArrowLeft, DArrowRight, House, Service, User, List, DataLine, Setting, Document, Calendar, Operation } from '@element-plus/icons-vue';
  import { computed, defineEmits, defineProps, ref, onMounted, markRaw } from 'vue';
  import { useRouter } from 'vue-router';
  import { useTabStore } from '../../stores/tabStore';

  const props = defineProps({
    activeMenu: {
      type: String,
      default: '/',
    },
  });
  const tabStore = useTabStore();
  const router = useRouter();
  const isCollapse = ref(false)
  const activeIndex = computed({
    get: () => tabStore.activeTab,
    set: (value) => tabStore.switchTab(value),
  });
  const activeTab = computed({
    get: () => tabStore.activeTab,
    set: (value) => tabStore.switchTab(value),
  });
  const menuList = ref([
    {
      index: '/',
      name: '首页',
      icon: House,
      children: [
        {
          index: '/',
          name: '首页',
        },
      ],
    },
    {
      index: '/consultingService',
      name: '咨询服务',
      icon: Service,
      children: [
        {
          index: '/onlineConsultation',
          name: '在线咨询',
          keepAlive: false,
        },
        {
          index: '/telephoneConsultation',
          name: '电话咨询',
          keepAlive: false,
        },
        {
          index: '/intelligentCustomerService',
          name: '智能客服',
          keepAlive: false,
        },
        {
          index: '/callRecords',
          name: '通话记录',
          keepAlive: false,
        },
      ],
    },
    {
      index: '/patient',
      name: '患者管理',
      icon: User,
      children: [
        {
          index: '/patient/info',
          name: '患者信息录入',
          keepAlive: false,
        },
        {
          index: '/patient/list',
          name: '患者列表',
          keepAlive: false,
        },
        {
          index: '/patient/archives',
          name: '患者档案管理',
          keepAlive: false,
        },
        {
          index: '/patient/followup',
          name: '患者随访计划',
          keepAlive: false,
        },
      ],
    },
    {
      index: '/doctor',
      name: '医生管理',
      icon: User,
      children: [
        {
          index: '/doctor/index',
          name: '医生列表',
          keepAlive: false,
        },
      ],
    },
    {
      index: '/diseaseSource',
      name: '病源建设',
      icon: Document,
      children: [
        {
          index: '/patient/segmentation',
          name: '患者细分与精准营销',
          keepAlive: false,
        },
        {
          index: '/memberManagement',
          name: '会员管理',
          keepAlive: false,
        },
        {
          index: '/patientRecommend',
          name: '口碑营销与患者推荐',
          keepAlive: false,
        },        
      ],
    },
    {
      index: '/reservation',
      name: '预约管理',
      icon: Calendar,
      children: [
        {
          index: '/reservationRegister',
          name: '预约挂号',
          keepAlive: false,
        },
        {
          index: '/reservationReminderChange',
          name: '预约提醒与变更',
          keepAlive: false,
        },
        {
          index: '/reservationInspectTest',
          name: '预约检查与检验',
          keepAlive: false,
        },
        {
          index: '/reservationRecords',
          name: '预约记录',
          keepAlive: false,
        },
      ],
    },
    {
      index: '/dataAnalysis',
      name: '数据分析',
      icon: DataLine,
      children: [
        {
          index: '/patientDataAnalysis',
          name: '患者数据分析',
          keepAlive: false,
        },
        {
          index: '/businessDataAnalysis',
          name: '业务数据分析',
          keepAlive: false,
        },
        {
          index: '/marketingEffectAnalysis',
          name: '营销效果分析',
          keepAlive: false,
        },
      ],
    },
    {
      index: '/system',
      name: '系统管理',
      icon: Setting,
      children: [
        {
          index: '/system/user',
          name: '用户管理',
          keepAlive: false,
        }
      ]
    }
  ])
  
  const emit = defineEmits(['menu-click'])
  
  function handleOpen(key: string, keyPath: string[]) {    
  }
  function handleClose(key: string, keyPath: string[]) {
  }
  
  function handleSelect(index: string, path: string[]) {
    try {
      activeIndex.value = index;
      const routePath = typeof path === 'string' ? path : index;
      router.push({ path: routePath }).catch(() => {});
      
      // 获取菜单项名称
      const menuItem = findMenuItem(index);
      if (menuItem) {
        emit('menu-click', { 
          index, 
          path: routePath,
          name: menuItem.name 
        });
        tabStore.addTab({ 
          name: menuItem.name, 
          index 
        });
        tabStore.switchTab(index);
      }
    } catch (error) {
      console.error('菜单选择失败:', error);
    }
  }

  // 查找菜单项
  const findMenuItem = (index: string) => {
    for (const item of menuList.value) {
      if (item.index === index) return item;
      const child = item.children?.find(child => child.index === index);
      if (child) return child;
    }
    return null;
  }

  // 使用 computed 优化过渡效果
  const menuStyle = computed(() => ({
    transition: 'width 0.3s cubic-bezier(0.4, 0, 0.2, 1)',
    width: isCollapse.value ? '64px' : '200px'
  }))

  // 优化收起逻辑
  const toggleCollapse = () => {
    // 使用 requestAnimationFrame 确保在下一帧执行状态更新
    requestAnimationFrame(() => {
      isCollapse.value = !isCollapse.value
    })
  }

  // 使用 markRaw 包装图标组件
  const icons = {
    DArrowLeft: markRaw(DArrowLeft),
    DArrowRight: markRaw(DArrowRight)
  };

  // 处理菜单数据，确保图标被 markRaw 包装
  menuList.value = menuList.value.map(item => ({
    ...item,
    icon: markRaw(item.icon)
  }));

  onMounted(() => {
    // 确保当前路由状态与 tab store 同步
    if (router.currentRoute.value.path && !router.currentRoute.value.meta.noTab) {
      tabStore.initializeFromRoute(router.currentRoute.value)
    }
  })
</script>

<style scoped>
.side-container {
  @apply flex flex-col h-full bg-white border-r border-gray-200 transition-all duration-300 relative;
  width: 200px;
}

.side-container.is-collapse {
  width: 64px;
}

.menu-wrapper {
  @apply flex-1 overflow-hidden hover:overflow-y-auto;
  height: calc(100vh - var(--ep-menu-item-height) - 48px);
}

/* 菜单基础样式 */
.el-menu-vertical {
  @apply border-none;
}

/* 滚动条样式 */
.menu-wrapper::-webkit-scrollbar {
  @apply w-1.5;
}

.menu-wrapper::-webkit-scrollbar-track {
  @apply bg-transparent;
}

.menu-wrapper::-webkit-scrollbar-thumb {
  @apply bg-gray-300 rounded-full transition-colors duration-300;
}

.menu-wrapper::-webkit-scrollbar-thumb:hover {
  @apply bg-gray-400;
}

/* 菜单项样式 */
:deep(.el-menu-item) {
  @apply transition-all duration-300;
}

:deep(.el-menu-item:hover) {
  @apply bg-blue-50;
}

:deep(.el-menu-item.is-active) {
  @apply bg-blue-100 !text-blue-600;
}

/* 折叠菜单样式 */
:deep(.el-menu--collapse) {
  width: 64px;
}

:deep(.el-menu--collapse .el-sub-menu__title) {
  @apply px-5;
}

/* 弹出菜单样式 */
:deep(.el-menu--popup) {
  @apply min-w-[160px] p-1 rounded-lg;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-menu--popup .el-menu-item) {
  @apply h-10 leading-10 px-4 rounded-md mx-0 my-1;
  min-width: 160px;
}

:deep(.el-menu--popup .el-menu-item:hover) {
  @apply bg-blue-50;
}

:deep(.el-menu--popup .el-menu-item.is-active) {
  @apply bg-blue-100 !text-blue-600;
}

/* 展开/收起按钮样式 */
.toggle-wrapper {
  @apply absolute -right-5 top-[45%] z-10;
}

.collapse-btn {
  @apply w-5 h-20 flex items-center justify-center cursor-pointer transition-all duration-300;
  background: linear-gradient(to right, #f0f2f5, #ffffff);
  border: 1px solid #e4e7ed;
  border-left: none;
  border-radius: 0 4px 4px 0;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.05);
}

.collapse-btn:hover {
  @apply bg-white;
  box-shadow: 4px 0 12px rgba(0, 0, 0, 0.08);
}

.collapse-icon {
  @apply text-gray-400 transition-all duration-300 text-sm;
}

.collapse-btn:hover .collapse-icon {
  @apply text-red-500;
}

/* 菜单图标样式 */
:deep(.el-sub-menu .el-icon),
:deep(.el-menu-item .el-icon) {
  @apply flex items-center justify-center text-base;
}

/* 自定义弹出菜单样式 */
:global(.custom-popper) {
  @apply border border-gray-200 rounded-lg !important;
}
</style>